package org.ru.mse10.cvis.web.validator;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.naming.NamingException;

import org.ru.mse10.cvis.service.UserService;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class ExistingUserEmailValidator.
 */
@FacesValidator(value = "existingUserEmailValidator")
public class ExistingUserEmailValidator implements Validator {

	/** The context. */
	private final FacesContext context = FacesContext.getCurrentInstance();

	/** The bundle. */
	private final ResourceBundle bundle = context.getApplication()
			.getResourceBundle(context, "message");

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		try {
			UserService userService = CommonUtil
					.lookupService(UserService.class);
			if (userService.isExistingUserEmail((String) value)) {
				throw new ValidatorException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						bundle.getString("existingUserEmailValidator"), null));
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

}
